<template>
  <div class="login-container">
    <div id="jparticles"></div>
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>系统登录</span>
        </div>
      </template>
      <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              :prefix-icon="Key"
              style="width: 60%;"
            ></el-input>
            <canvas
              ref="captchaCanvas"
              @click="refreshCaptcha"
              class="captcha-canvas"
            ></canvas>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleLogin"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { login } from '@/api/user'
import { User, Lock, Key } from '@element-plus/icons-vue'

// 定义登录响应类型接口
interface LoginResponse {
  code: number
  message: string
  token: string
  userInfo: {
    id: number
    username: string
    avatar: string
    roles: string[]
  }
}
import { Particle } from 'jparticles'

const router = useRouter()
const loginForm = reactive<{ username: string; password: string; captcha: string }>({
  username: 'admin',
  password: 'admin123',
  captcha: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
}

const loading = ref(false)
const loginFormRef = ref()
let JP = ref()
const captchaCanvas = ref<HTMLCanvasElement>()
let captchaCode = ref('')

const handleLogin = async () => {
  try {
    // 验证表单
    await loginFormRef.value.validate()

    // 验证验证码
    if (loginForm.captcha.toLowerCase() !== captchaCode.value.toLowerCase()) {
      ElMessage.error('验证码错误')
      refreshCaptcha()
      return
    }

    loading.value = true

    // 调用登录接口
    const res = await login(loginForm) as unknown as LoginResponse
    if (res) {
      // 保存token和用户信息
      localStorage.setItem('token', res.token)
      localStorage.setItem('userInfo', JSON.stringify(res.userInfo))

      ElMessage.success('登录成功')
      // 跳转到首页
      router.push('/')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 生成验证码
function generateCaptcha() {
  if (!captchaCanvas.value) return

  const canvas = captchaCanvas.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // 设置canvas尺寸
  canvas.width = 120
  canvas.height = 40

  // 生成随机验证码
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  let code = ''
  for (let i = 0; i < 4; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  captchaCode.value = code

  // 绘制背景
  ctx.fillStyle = '#f5f7fa'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }

  // 绘制干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.beginPath()
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI)
    ctx.fill()
  }

  // 绘制验证码
  ctx.font = 'bold 20px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  for (let i = 0; i < code.length; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 100 + 50}, ${Math.random() * 100 + 50}, ${Math.random() * 100 + 50})`
    ctx.fillText(code.charAt(i), 30 + i * 20, 20, 20)
  }
}

// 刷新验证码
function refreshCaptcha() {
  generateCaptcha()
}

function handleInitJparticles() {
  JP.value = new Particle('#jparticles', {
    color: '#25bfff',
    lineShape: 'spider',
    range: 3000,
    proximity: 150,
    parallax: true,
  })
}

onMounted(() => {
  handleInitJparticles()
  // 初始化验证码
  setTimeout(() => {
    generateCaptcha()
  }, 0)
  document.addEventListener('resize', () => {
    console.log('resize');
  })
})
</script>

<style lang="scss" scoped>
#jparticles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  overflow: hidden;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
}

.login-card {
  position: relative;
  z-index: 10;
  width: 400px;
}

.card-header {
  display: flex;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

.login-form {
  margin-top: 20px;
}

.captcha-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.captcha-canvas {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}
</style>